import os
import tkinter as tk
from pathlib import Path
from tkinter import Menu


def toggle_fullscreen(root):
    root.attributes("-fullscreen", not root.attributes("-fullscreen"))


def maximize_window(root):
    root.state("zoomed")
    root.after(100, root.attributes, '-topmost', True)
    root.after(100, root.attributes, '-topmost', False)


def gui_show_files(files):
    root = tk.Tk()
    root.title("文件管理器")
    maximize_window(root)
    scrollbar = tk.Scrollbar(root)
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    listbox = tk.Listbox(root, yscrollcommand=scrollbar.set)
    listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=10, pady=10)
    scrollbar.config(command=listbox.yview)

    def open_file():
        selected_file = listbox.get(listbox.curselection())
        os.system(rf'''start "" "{selected_file}"''')

    def open_folder():
        index = listbox.curselection()
        print(index)
        if index == ():
            return
        selected_file = listbox.get(index)
        # folder = Path(selected_file).parent.absolute()
        # open_folder_cmd = rf'explorer "{folder}"'
        # print(open_folder_cmd)
        # os.system(open_folder_cmd)
        absf = Path(selected_file).absolute()
        open_folder_cmd = rf'explorer /select,"{absf}"'
        print(open_folder_cmd)
        os.system(open_folder_cmd)

    def on_double_click(event):
        open_file()

    listbox.bind('<Double-Button-1>', on_double_click)

    menu = Menu(root, tearoff=0)
    menu.add_command(label="打开文件夹", command=open_folder)

    def show_context_menu(event):
        menu.post(event.x_root, event.y_root)

    listbox.bind('<Button-3>', show_context_menu)

    for file in files:
        listbox.insert(tk.END, file)

    open_button = tk.Button(root, text="打开", command=open_file)
    open_button.pack()

    root.mainloop()


if __name__ == '__main__':
    gui_show_files(['requirements.txt', 'f'])
